//===============================================================================
// Microsoft patterns & practices
// Smart Client Software Factory 2010
//===============================================================================
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================
//----------------------------------------------------------------------------------------
// patterns & practices - Smart Client Software Factory - Guidance Package
//
// This file was generated by the "Add View" recipe.
//
// A presenter calls methods of a view to update the information that the view displays. 
// The view exposes its methods through an interface definition, and the presenter contains
// a reference to the view interface. This allows you to test the presenter with different 
// implementations of a view (for example, a mock view).
//
// For more information see:
// ms-help://MS.VSCC.v90/MS.VSIPCC.v90/ms.practices.scsf.2008apr/SCSF/html/02-09-010-ModelViewPresenter_MVP.htm
//
// Latest version of this Guidance Package: http://go.microsoft.com/fwlink/?LinkId=62182
//----------------------------------------------------------------------------------------

using System;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI;
using QuickStart.Infrastructure.Interface;
using QuickStart.RestaurantModule.DSA.MenuServiceClient;
using QuickStart.RestaurantModule.RestaurantService;
using Microsoft.Practices.CompositeUI.EventBroker;
using QuickStart.RestaurantModule.Constants;
using QuickStart.RestaurantModule.Properties;
using Microsoft.Practices.SmartClient.DisconnectedAgent;

namespace QuickStart.RestaurantModule
{
    public partial class RestaurantsViewPresenter : Presenter<IRestaurantsView>
    {
        [EventPublication(EventTopicNames.LongProcess, PublicationScope.WorkItem)]
        public event EventHandler<EventArgs> LongProcess;
    
        [EventPublication(EventTopicNames.RestaurantSelected, PublicationScope.Descendants)]
        public event EventHandler<EventArgs<Restaurant>> RestaurantSelected;
        
        [EventPublication(EventTopicNames.StatusUpdate, PublicationScope.Global)]
        public event EventHandler<EventArgs<string>> StatusUpdate;

		Agent _restaurantService;
        IConnectionMonitor _connectionMonitor;

        public RestaurantsViewPresenter
            (
				[ServiceDependency] Agent restaurantService,
                [ServiceDependency] IConnectionMonitor connectionMonitor
            )
        {
            _connectionMonitor = connectionMonitor;
            _restaurantService = restaurantService;
            
            // Subscribe to the service agent callback events
            Callback.GetRestaurantsReturn += new EventHandler<EventArgs<Restaurant[]>>(GetRestaurantsReturn);
			Callback.GetRestaurantsException += new EventHandler<EventArgs<Exception>>(GetRestaurantsException);
        }

        /// <summary>
        /// This method is a placeholder that will be called by the view when it has been loaded.
        /// </summary>
        public override void OnViewReady()
        {
            TryGetRestaurants();
        }
        
        /// <summary>
        /// Close the view
        /// </summary>
        public void OnCloseView()
        {
            base.CloseView();
        }

        /// <summary>
        /// Tries to get the restaurants list. If the application is offline, it will enqueue
        /// the request for further dispatching and update the view to show an offline message.
        /// </summary>
        public void TryGetRestaurants()
        {
            if (Connected)
            {
                OnLongProcess(true);
                OnStatusUpdate(Resources.RetrievingRestaurantsList);
            }
            else
            {
                // If the application is not online, update the view to show an offline message
                View.ShowOfflineMessage();
            }
            
            // Enqueue a request. The request will be dispatched when a connection is detected.
            _restaurantService.GetRestaurants();
        }

        public void OnRestaurantSelected(Restaurant restaurant)
        {
            if (RestaurantSelected != null)
            {
                RestaurantSelected(this, new EventArgs<Restaurant>(restaurant));
            }
        }

        /// <summary>
        /// This method will be called when the service agent gets a
        /// successful response from the GetRestaurants method.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">GetRestaurants return value</param>
        private void GetRestaurantsReturn(object sender, EventArgs<Restaurant[]> e)
        {
            OnLongProcess(false);
            OnStatusUpdate(Resources.RestaurantsListRecieved);
            View.ShowRestaurants(e.Data);
        }

        /// <summary>
        /// This method will be called when the service agent gets an
        /// exception when calling the GetRestaurants method.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Exception thrown</param>
        private void GetRestaurantsException(object sender, EventArgs<Exception> e)
        {
            OnLongProcess(false);
            if (Connected)
            {
                OnStatusUpdate(Resources.ErrorRetrievingRestaurantsList);
                View.ShowConnectionError();
            }
            else
            {
                View.ShowOfflineMessage();
            }
        }

        private bool Connected
        {
            get { return _connectionMonitor.IsConnected; }
        }

        private void OnLongProcess(bool running)
        {
            if (LongProcess != null)
            {
                LongProcess(this, new EventArgs<bool>(running));
            }
        }

        private void OnStatusUpdate(string message)
        {
            if (StatusUpdate != null)
            {
                StatusUpdate(this, new EventArgs<string>(message));
            }
        }
    }
}

